import tornado.web

import datetime
import controller.base
from util.misc import *


class UserHandler(controller.base.BaseHandler):
    def put(self):
        phone = self.get_body_para("phoneNo")
        password = self.get_body_para("password")
        old_password = self.get_body_para("oldPassword")

        if phone is None or password is None or old_password is None:
            self.rsp(7, msg="parameter error")
            return

        sql = 'SELECT * FROM users WHERE phone = %s AND password = %s'
        res = self.db.get(sql, phone, get_md5(old_password))

        if res is None:
            self.rsp(7, msg="phone or password error")
            return

        # sql = 'SELECT * FROM users WHERE phone = %s'
        # res = self.db.get(sql, phone)
        # if res is None:
        #     self.rsp(6, msg="phone number not registered")
        #     return

        password = get_md5(password)
        token = random_str(64)
        expire = (datetime.datetime.now()+datetime.timedelta(days=3650)).strftime("%Y-%m-%d %H:%M:%S")
        sql = "UPDATE users SET password = %s, token = %s, expire = %s WHERE id = %s"
        res1 = self.db.update(sql, password, token, expire, res["id"])
        data = {
            "user": {
                "id": res["id"],
                "phoneNo": phone
            },
            "session": {
                "token": token,
                "expire": expire
            }
        }
        self.rsp(0, data)

    def post(self):
        phone = self.get_body_para("phoneNo")
        password = self.get_body_para("password")
        code = self.get_body_para("verifyCode")

        if phone is None or password is None or code is None:
            self.rsp(7, msg="parameter error")
            return

        password = get_md5(password)
        if not self.verify_code(phone, code):
            self.rsp(5, msg="code error")
            return
        sql = 'SELECT * FROM users WHERE phone = %s'
        user = self.db.get(sql, phone)
        if user is not None:
            self.rsp(6, msg="phone number registered")
            return
        token = random_str(64)
        expire = (datetime.datetime.now()+datetime.timedelta(days=3650)).strftime("%Y-%m-%d %H:%M:%S")
        sql = "INSERT INTO users (phone,password,token,expire,createTime) VALUES (%s,%s,%s,%s,%s)"
        res = self.db.insert(sql, phone, password, token, expire, datetime.datetime.now().strftime("%y-%m-%d %H:%M:%S"))
        data = {
            "user": {
                "id": res,
                "phoneNo": phone
            },
            "session": {
                "token": token,
                "expire": expire
            }
        }
        self.rsp(0, data)

    def verify_code(self, phone, code, sms_type=1):
        sql = 'SELECT * FROM smscodes WHERE phone = %s AND type = %s  AND code = %s'
        sms = self.db.get(sql, phone, sms_type, code)
        if sms is None:
            return False
        elif datetime.datetime.now() - sms['createTime'] <= datetime.timedelta(seconds=300):
            return True
        return False


class SessionHandler(controller.base.BaseHandler):
    def post(self):
        phone = self.get_body_para("phoneNo")
        password = self.get_body_para("password")
        if phone is None or password is None:
            self.rsp(5, msg="code error")
            return

        sql = 'SELECT * FROM users WHERE phone = %s AND password = %s'
        res = self.db.get(sql, phone, get_md5(password))

        if res is None:
            self.rsp(7, msg="phone or password error")
            return
        token = random_str(64)
        expire = (datetime.datetime.now()+datetime.timedelta(days=3650)).strftime("%Y-%m-%d %H:%M:%S")
        sql = "UPDATE users SET token = %s, expire = %s WHERE id = %s"
        res1 = self.db.update(sql, token, expire, res["id"])
        data = {
            "user": {
                "id": res["id"],
                "phoneNo": phone
            },
            "session": {
                "token": token,
                "expire": expire
            }
        }
        self.rsp(0, data)


class ForgetHandler(controller.base.BaseHandler):
    def put(self):
        phone = self.get_body_para("phoneNo")
        password = self.get_body_para("password")
        code = self.get_body_para("verifyCode")

        if phone is None or password is None or code is None:
            self.rsp(7, msg="parameter error")
            return

        if not self.verify_code(phone, code, 2):
            self.rsp(5, msg="code error")
            return

        sql = 'SELECT * FROM users WHERE phone = %s'
        res = self.db.get(sql, phone)
        if res is None:
            self.rsp(6, msg="phone number not registered")
            return

        password = get_md5(password)
        token = random_str(64)
        expire = (datetime.datetime.now()+datetime.timedelta(days=3650)).strftime("%Y-%m-%d %H:%M:%S")
        sql = "UPDATE users SET password = %s, token = %s, expire = %s WHERE id = %s"
        res1 = self.db.update(sql, password, token, expire, res["id"])
        data = {
            "user": {
                "id": res["id"],
                "phoneNo": phone
            },
            "session": {
                "token": token,
                "expire": expire
            }
        }
        self.rsp(0, data)

    def verify_code(self, phone, code, sms_type=1):
        sql = 'SELECT * FROM smscodes WHERE phone = %s AND type = %s  AND code = %s'
        sms = self.db.get(sql, phone, sms_type, code)
        if sms is None:
            return False
        elif datetime.datetime.now() - sms['createTime'] <= datetime.timedelta(seconds=300):
            return True
        return False
